<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="课程名称" v-bind="validateInfos.title">
            <a-input v-model:value="formData.title" placeholder="请选择课程名称" :disabled="true"></a-input>
            <!-- <j-dict-select-tag v-model:value="formData.title" dictCode="" placeholder="请选择课程名称" :disabled="disabled"/> -->
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程描述" v-bind="validateInfos.description">
            <a-input v-model:value="formData.description" placeholder="请输入课程描述" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="教师姓名" v-bind="validateInfos.teachername">
            <a-input v-model:value="formData.teachername" placeholder="请输入教师姓名" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程图片" v-bind="validateInfos.imageurl">
            <j-image-upload v-model:value="formData.imageurl" :disabled="true"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="选课人数" v-bind="validateInfos.curriculavariablecount">
            <a-input-number v-model:value="formData.curriculavariablecount" placeholder="请输入选课人数" style="width: 100%"
              :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程详情" v-bind="validateInfos.coursedetail">
            <j-editor v-model:value="formData.coursedetail" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程时长" v-bind="validateInfos.courseduration">
            <a-input v-model:value="formData.courseduration" placeholder="请输入课程时长" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程节数" v-bind="validateInfos.coursepitchnumber">
            <a-input v-model:value="formData.coursepitchnumber" placeholder="请输入课程节数" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="学习记录" key="studyRecord" :forceRender="true">
        <j-vxe-table :keep-source="true" resizable ref="studyRecordTableRef" :loading="studyRecordTable.loading"
          :columns="studyRecordTable.columns" :dataSource="studyRecordTable.dataSource" :height="340"
          :disabled="disabled" :rowNumber="true" :rowSelection="true" :toolbar="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
import { queryStudyRecordListByMainId, queryDataById, saveOrUpdate } from '../MyCourseManagement.api';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { studyRecordColumns } from '../MyCourseManagement.data';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
import { Form } from 'ant-design-vue';
import { saveStudyRecordAdmin } from '../../courseManagement/studyRecordAdmin/StudyRecordAdmin.api';
const useForm = Form.useForm;

export default defineComponent({
  name: "MyCourseManagementForm",
  components: {
    JDictSelectTag,
    JImageUpload,
    JEditor,
    JVxeTable,
  },
  props: {
    formDisabled: {
      type: Boolean,
      default: false
    },
    formData: { type: Object, default: () => { } },
    formBpm: { type: Boolean, default: true }
  },
  emits: ['success'],
  setup(props, { emit }) {
    const loading = ref(false);
    const studyRecordTableRef = ref();
    const studyRecordTable = reactive<Record<string, any>>({
      loading: false,
      columns: studyRecordColumns,
      dataSource: []
    });
    const activeKey = ref('studyRecord');
    const formData = reactive<Record<string, any>>({
      id: '',
      title: '',
      description: '',
      teachername: '',
      imageurl: '',
      curriculavariablecount: undefined,
      coursedetail: '',
      courseduration: '',
      coursepitchnumber: '',
    });

    //表单验证
    const validatorRules = reactive({
      title: [{ required: true, message: '请输入课程名称!' },],
      description: [{ required: true, message: '请输入课程描述!' },],
      teachername: [{ required: true, message: '请输入教师姓名!' },],
    });
    const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
    const dbData = {};
    const formItemLayout = {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
    };

    // 表单禁用
    const disabled = computed(() => {
      if (props.formBpm === true) {
        if (props.formData.disabled === false) {
          return false;
        } else {
          return true;
        }
      }
      return props.formDisabled;
    });



    function add() {
      resetFields();
      studyRecordTable.dataSource = [];
    }

    async function edit(row) {
      //主表数据
      await queryMainData(row.id);
      //子表数据
      const studyRecordDataList = await queryStudyRecordListByMainId(row['id']);
      studyRecordTable.dataSource = [...studyRecordDataList];
    }

    async function queryMainData(id) {
      const row = await queryDataById(id);
      Object.keys(row).map(k => {
        formData[k] = row[k];
      });
    }

    const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
      'studyRecord': studyRecordTableRef,
    });

    async function getFormData() {
      await validate();
      return transformData(toRaw(formData))
    }

    async function submitForm() {
      const mainData = await getFormData();
      const subData = await getSubFormAndTableData();
      console.log('表单提交数据  mainData', subData)
      const newData = []
      if (subData?.studyRecordList) {
        (subData?.studyRecordList || []).forEach(element => {
          const params = {
            endtime: element.endtime,
            starttime: element.starttime,
            isSignString: element.isSignString,
            muCourseId: mainData.id,
            muCourseName: mainData.title,
            teacherName: mainData.teachername,
            status: element.status || '0',
          }
          newData.push(params)
        });
      }
      // { studyRecordList: newData }
      const values = Object.assign({}, dbData, mainData, { studyRecordList: newData });
      console.log('表单提交数据', values)
      const isUpdate = values.id ? true : false
      await saveOrUpdate(values, isUpdate);

      emit('success');
    }

    function setFieldsValue(values) {
      if (values) {
        Object.keys(values).map(k => {
          formData[k] = values[k];
        });
      }
    }

    /**
     * 值改变事件触发-树控件回调
     * @param key
     * @param value
     */
    function handleFormChange(key, value) {
      formData[key] = value;
    }


    return {
      studyRecordTableRef,
      studyRecordTable,
      validatorRules,
      validateInfos,
      activeKey,
      loading,
      formData,
      setFieldsValue,
      handleFormChange,
      formItemLayout,
      disabled,
      getFormData,
      submitForm,
      add,
      edit
    }
  }
});
</script>
